import axios from 'axios'
import Message from '../message'
import { LoadingBar } from 'view-ui-plus'
import { getToken } from './token.js'
import router from "../router";

// 本地开发环境 , http://www.haredot.com:81
const LOCAL_URL = "http://localhost:8080" ;

const instance = axios.create({
    baseURL: LOCAL_URL ,
});

// axios 发送请求前 进行统一的拦截
instance.interceptors.request.use(async function (config) {
    LoadingBar.start();
    // 判断当前请求地址是不是 /api/token
    if (config.url !== "/api/token") {
        // 获取 访问令牌
        try{
            let accessToken = await getToken() ;
            if (accessToken != null) {
                // 添加一个请求头信息
                let headers = config.headers ?? {} ;
                headers["Authorization"] = "Bearer " + accessToken ;
                config.headers = headers ;
            }
        }catch (e){
            // 跳转到登录
            router.push("/login")
            return Promise.reject(e.response.message);
        }
    }
    return config ;
});

// 给 axios 响应 进行拦截，统一处理 异常状态的 提示
instance.interceptors.response.use(function(response) {
    LoadingBar.finish();
    let ret = response.data ;
    if (!ret.status && (ret.code === 20000 || ret.code === 40000 || ret.code === 50000 || ret.code === 60000 || ret.code === 70000 || ret.code === 99999 )) {
        Message.error(ret.message);
        throw ret.message ;
    }
    return response ;
}, function(error){
    LoadingBar.error();
    Message.error("未知错误、错误码：" + error.code);
    throw error ;
});

export default instance ;